/**
 * 
 * @param {Function} fn  需要节流处理的函数 
 * @param {Number} interval  延时时间
 * @param {Object} options 配置选项
 * @returns 
 */
export default function (fn, interval, options = {
  leading: true,
  trailing: false,
  resultCallback: null
}) {
  const {
    leading,
    trailing,
    resultCallback
  } = options
  let lastTime = 0
  let timer = null
  const _throttle = function (...args) {
    return new Promise((resolve, reject) => {
      const nowTime = new Date().getTime()
      if (!lastTime && !leading) lastTime = nowTime
      // 剩余时间 = 设定间隔时间 - (点击时间 - 上次点击时间)
      const remianTime = interval - (nowTime - lastTime)
      if (remianTime <= 0) {
        if (timer) {
          clearTimeout(timer)
          timer = null
        }
        try {
          const res = fn.apply(this, args)
          if (resultCallback) resultCallback(res)
          resolve(res)
        } catch (error) {
          reject(error)
        }
        lastTime = nowTime
        return
      }
      if (trailing && !timer) {
        timer = setTimeout(() => {
          timer = null
          lastTime = !leading ? 0 : new Date().getTime()
          try {
            const res = fn.apply(this, args)
            if (resultCallback) resultCallback(res)
            resolve(res)
          } catch (error) {
            reject(error)
          }
        }, remianTime)
      }
    })
  }
  _throttle.cancel = function () {
    if (timer) clearTimeout(timer)
    timer = null
    lastTime = 0
  }
  return _throttle
}